<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.css">
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yimig.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="先说思路：在主页面里添加两个控件：顶部的文本框和下方承载按钮的面板控件，然后在下方的面板控件中依次填入按钮。 但是这里还有一个问题就是如何填入大量的按钮。16个按钮一个一个实例化再填入将会造成较大的工作量，但是像课本中那样写个名字数组再一股脑地实例化又会破坏语义性，在后期我们绑定事件时造成非常大的麻烦。为了在其中找到一个折中点，我们选用数字按钮使用数组实例化，而功能按钮（加减乘除等）单独实例化。">
<meta property="og:type" content="article">
<meta property="og:title" content="【Java】可连续计算的整数计算器">
<meta property="og:url" content="http://yimig.github.io/2018/12/08/proj_javafx_calculator/index.html">
<meta property="og:site_name" content="Tim&#39;s Blog">
<meta property="og:description" content="先说思路：在主页面里添加两个控件：顶部的文本框和下方承载按钮的面板控件，然后在下方的面板控件中依次填入按钮。 但是这里还有一个问题就是如何填入大量的按钮。16个按钮一个一个实例化再填入将会造成较大的工作量，但是像课本中那样写个名字数组再一股脑地实例化又会破坏语义性，在后期我们绑定事件时造成非常大的麻烦。为了在其中找到一个折中点，我们选用数字按钮使用数组实例化，而功能按钮（加减乘除等）单独实例化。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://upane.cn/wp-content/uploads/2018/12/java_2018-12-19_11-16-37.png">
<meta property="article:published_time" content="2018-12-08T01:44:56.000Z">
<meta property="article:modified_time" content="2020-10-28T14:53:08.071Z">
<meta property="article:author" content="Tim">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="课堂作业">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://upane.cn/wp-content/uploads/2018/12/java_2018-12-19_11-16-37.png">

<link rel="canonical" href="http://yimig.github.io/2018/12/08/proj_javafx_calculator/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【Java】可连续计算的整数计算器 | Tim's Blog</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64126ab668fa908027cba9464a0afec7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Tim's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Learn Everything!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/schedule/" rel="section"><i class="fa fa-fw fa-calendar"></i>日程表</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/yimig" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yimig.github.io/2018/12/08/proj_javafx_calculator/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Tim">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tim's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【Java】可连续计算的整数计算器
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-12-08 09:44:56" itemprop="dateCreated datePublished" datetime="2018-12-08T09:44:56+08:00">2018-12-08</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-10-28 22:53:08" itemprop="dateModified" datetime="2020-10-28T22:53:08+08:00">2020-10-28</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Project/" itemprop="url" rel="index"><span itemprop="name">Project</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Project/HomeWork/" itemprop="url" rel="index"><span itemprop="name">HomeWork</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              <span>5k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><strong>先说思路：在主页面里添加两个控件：顶部的文本框和下方承载按钮的面板控件，然后在下方的面板控件中依次填入按钮。</strong> 但是这里还有一个问题就是如何填入大量的按钮。16个按钮一个一个实例化再填入将会造成较大的工作量，但是像课本中那样写个名字数组再一股脑地实例化又会破坏语义性，在后期我们绑定事件时造成非常大的麻烦。为了在其中找到一个折中点，<strong>我们选用数字按钮使用数组实例化，而功能按钮（加减乘除等）单独实例化。</strong><br><a id="more"></a><br><a target="_blank" rel="noopener" href="http://upane.cn/wp-content/uploads/2018/12/java_2018-12-19_11-16-37.png"><img src="http://upane.cn/wp-content/uploads/2018/12/java_2018-12-19_11-16-37.png" alt=""></a> 注意看图，数字是倒序显示的，所以不要忘了在保存插入顺序的数组中倒序插入数字按钮。 <strong>内部逻辑：创立四个变量，用于存储第一个操作数（被加数/被减数/被乘数/被除数）、第二个操作数（加数/减数/乘数/除数）、运算符号（char）、判断目前操作数的Boolean判断值。 判断值初始化为False，表示操作第一个操作数，按下的数字将存储于此，按下运算符后，存储运算符号并改变判断值，移动到第二个操作数，等待用户输入。按下等于号后，判断运算符号并进行相应运算。</strong> 上代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.swing.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionEvent;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionListener;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainWindow</span> <span class="keyword">extends</span> <span class="title">JFrame</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> firstnum;<span class="comment">//第一个操作数</span></span><br><span class="line">    <span class="keyword">int</span> secondnum;<span class="comment">//第二个操作数</span></span><br><span class="line">    <span class="keyword">char</span> func;<span class="comment">//存储计算符号</span></span><br><span class="line">    <span class="keyword">boolean</span> isFirstnum=<span class="keyword">true</span>;<span class="comment">//存储是否已为第一个操作数赋值</span></span><br><span class="line">    TextField textField;<span class="comment">//存储显示框，否则子类无法得到值</span></span><br><span class="line"></span><br><span class="line">    MainWindow(String title)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">super</span>(title);<span class="comment">//调用JFrame的构造函数为窗口标题赋值</span></span><br><span class="line">        initializeWindow();<span class="comment">//初始化窗口</span></span><br><span class="line">        initializeControls();<span class="comment">//初始化控件</span></span><br><span class="line">        <span class="keyword">this</span>.setVisible(<span class="keyword">true</span>);<span class="comment">//设置窗口可见性 每次设置可见性时系统刷新窗口</span></span><br><span class="line">        <span class="comment">// 如果在这之前设置可见性会导致后面添加的控件知道界面再次刷新时才可见</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化窗口方法</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span>  <span class="title">initializeWindow</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.setSize(<span class="number">400</span>,<span class="number">200</span>);<span class="comment">//设置窗口大小</span></span><br><span class="line">        <span class="keyword">this</span>.setLocation(<span class="number">400</span>,<span class="number">400</span>);<span class="comment">//设置窗口首次出现的位置</span></span><br><span class="line">        <span class="keyword">this</span>.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<span class="comment">//设置用户点击退出时的策略</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化窗口内部的控件</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initializeControls</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        JButton[] buttons=<span class="keyword">new</span> JButton[<span class="number">10</span>];<span class="comment">//建立一个数组，用来存放数字按钮</span></span><br><span class="line">        JButton[] order = <span class="keyword">new</span> JButton[<span class="number">16</span>];<span class="comment">//建立一个数组，用来存放按钮在表格中的插入顺序</span></span><br><span class="line">        JPanel mainjp = <span class="keyword">new</span> JPanel(<span class="keyword">new</span> BorderLayout());<span class="comment">//实例化主窗口（承载边界停靠面板）的面板</span></span><br><span class="line">        JPanel buttonjp = <span class="keyword">new</span> JPanel(<span class="keyword">new</span> GridLayout(<span class="number">4</span>, <span class="number">4</span>));<span class="comment">//实例化存放按钮（承载表格面板）的面板</span></span><br><span class="line">        textField = <span class="keyword">new</span> TextField();<span class="comment">//实例化文本框</span></span><br><span class="line">        textField.setText(<span class="string">&quot;&quot;</span>);</span><br><span class="line">        mainjp.add(textField, BorderLayout.NORTH);<span class="comment">//将文本框固定在主窗口面板的上方</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; buttons.length; i++) &#123;</span><br><span class="line">            buttons[i] = <span class="keyword">new</span> JButton(Integer.toString(i));<span class="comment">//实例化数字按钮，并为其显示内容赋值</span></span><br><span class="line">            buttons[i].addActionListener(<span class="keyword">new</span> NumEventListener());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; buttons.length; i++) order[i] = buttons[buttons.length - i - <span class="number">1</span>];<span class="comment">//将数字按钮以倒序插入表格的插入顺序中（显示顺序为9→0）</span></span><br><span class="line">        JButton addition = <span class="keyword">new</span> JButton(<span class="string">&quot;+&quot;</span>);<span class="comment">//实例化控制按钮“加”，并为其显示内容赋值</span></span><br><span class="line">        addition.addActionListener(<span class="keyword">new</span> FuncEventListener());</span><br><span class="line">        order = insert(order, addition, <span class="number">3</span>);<span class="comment">//将其插入到表格插入顺序数组索引为3的位置（第一行最右边），以下同</span></span><br><span class="line">        JButton subtraction = <span class="keyword">new</span> JButton(<span class="string">&quot;-&quot;</span>);</span><br><span class="line">        subtraction.addActionListener(<span class="keyword">new</span> FuncEventListener());</span><br><span class="line">        order = insert(order, subtraction, <span class="number">7</span>);</span><br><span class="line">        JButton multiplication = <span class="keyword">new</span> JButton(<span class="string">&quot;*&quot;</span>);</span><br><span class="line">        multiplication.addActionListener(<span class="keyword">new</span> FuncEventListener());</span><br><span class="line">        order = insert(order, multiplication, <span class="number">11</span>);</span><br><span class="line">        JButton clear = <span class="keyword">new</span> JButton(<span class="string">&quot;AC&quot;</span>);</span><br><span class="line">        <span class="comment">//=========================================动作：按下AC按钮清空输入内容==============================================</span></span><br><span class="line">        clear.addActionListener(<span class="keyword">new</span> ActionListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span> </span>&#123;</span><br><span class="line">                firstnum=<span class="number">0</span>;</span><br><span class="line">                secondnum=<span class="number">0</span>;</span><br><span class="line">                isFirstnum=<span class="keyword">true</span>;</span><br><span class="line">                textField.setText(<span class="string">&quot;&quot;</span>);<span class="comment">//还原各值</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        order = insert(order, clear, <span class="number">13</span>);</span><br><span class="line">        JButton equal = <span class="keyword">new</span> JButton(<span class="string">&quot;=&quot;</span>);</span><br><span class="line">        <span class="comment">//========================================动作：按下等于按钮计算结果=================================================</span></span><br><span class="line">        equal.addActionListener(<span class="keyword">new</span> ActionListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">switch</span> (func)<span class="comment">//判断符号，运算出结果</span></span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="keyword">case</span> <span class="string">&#x27;+&#x27;</span> :textField.setText(String.valueOf(firstnum+secondnum));<span class="keyword">break</span>;</span><br><span class="line">                    <span class="keyword">case</span> <span class="string">&#x27;-&#x27;</span> :textField.setText(String.valueOf(firstnum-secondnum));<span class="keyword">break</span>;</span><br><span class="line">                    <span class="keyword">case</span> <span class="string">&#x27;*&#x27;</span> :textField.setText(String.valueOf(firstnum*secondnum));<span class="keyword">break</span>;</span><br><span class="line">                    <span class="keyword">case</span> <span class="string">&#x27;/&#x27;</span> :textField.setText(String.valueOf(firstnum/secondnum));<span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                isFirstnum=<span class="keyword">true</span>;<span class="comment">//还原输入数字的位置，以便连续计算</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">//=================================================================================================================</span></span><br><span class="line">        order = insert(order, equal, <span class="number">14</span>);</span><br><span class="line">        JButton division = <span class="keyword">new</span> JButton(<span class="string">&quot;/&quot;</span>);</span><br><span class="line">        division.addActionListener(<span class="keyword">new</span> FuncEventListener());</span><br><span class="line">        order = insert(order, division, <span class="number">15</span>);</span><br><span class="line">        <span class="keyword">for</span> (JButton button : order) buttonjp.add(button);<span class="comment">//以面板插入顺序数组的索引顺序为按钮面板添加按钮</span></span><br><span class="line">        mainjp.add(buttonjp, BorderLayout.CENTER);<span class="comment">//将按钮面板固定在主界面的中心</span></span><br><span class="line">        <span class="keyword">this</span>.add(mainjp);<span class="comment">//将主界面添加到该窗口</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//为插入数组而写的算法，将某个元素插入数组的某个位置，该位置后的元素依次后移</span></span><br><span class="line">    <span class="comment">//传入值为操作的数组、插入的元素、插入元素的索引，返回值为修改完毕的数组</span></span><br><span class="line">    <span class="keyword">private</span> JButton[] insert(JButton[] order, JButton newbutton, <span class="keyword">int</span> index)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//元素按照索引顺序依次后移一位，直到检测到索引位置</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = order.length - <span class="number">1</span>; i &gt; index; i--) &#123;</span><br><span class="line">            order[i] = order[i - <span class="number">1</span>];</span><br><span class="line">        &#125;</span><br><span class="line">        order[index] = newbutton;<span class="comment">//将索引位置的元素替换为新元素</span></span><br><span class="line">        <span class="keyword">return</span> order;<span class="comment">//返回修改后的数组</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//数字按钮的按下动作</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">NumEventListener</span> <span class="keyword">implements</span> <span class="title">ActionListener</span></span></span><br><span class="line"><span class="class">    </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            JButton button=(JButton)e.getSource();<span class="comment">//得到被按下的按钮</span></span><br><span class="line">            textField.setText(textField.getText() + button.getText());<span class="comment">//连续添加数字，以得到多位数字</span></span><br><span class="line">            <span class="keyword">if</span> (isFirstnum) firstnum = Integer.parseInt(textField.getText());<span class="comment">//判断输入的位置</span></span><br><span class="line">            <span class="keyword">else</span> secondnum = Integer.parseInt(textField.getText());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//功能按钮（运算符号）的按下动作</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">FuncEventListener</span> <span class="keyword">implements</span> <span class="title">ActionListener</span></span></span><br><span class="line"><span class="class">    </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            JButton button=(JButton)e.getSource();<span class="comment">//得到被按下的按钮</span></span><br><span class="line">            func=button.getText().charAt(<span class="number">0</span>);<span class="comment">//将按钮代表的符号存到func变量</span></span><br><span class="line">            isFirstnum=<span class="keyword">false</span>;<span class="comment">//移动输入位置到第二个操作数</span></span><br><span class="line">            firstnum=Integer.parseInt(textField.getText());<span class="comment">//将目前的值存入第一个操作数，以便连续运算</span></span><br><span class="line">            textField.setText(<span class="string">&quot;&quot;</span>);<span class="comment">//清空显示框的内容</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
              <a href="/tags/%E8%AF%BE%E5%A0%82%E4%BD%9C%E4%B8%9A/" rel="tag"># 课堂作业</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/12/05/java_io/" rel="prev" title="【Java】IO流作业">
      <i class="fa fa-chevron-left"></i> 【Java】IO流作业
    </a></div>
      <div class="post-nav-item">
    <a href="/2018/12/20/coding_quick_sorting/" rel="next" title="【数据结构】快速排序">
      【数据结构】快速排序 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Tim"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Tim</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">90</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">40</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yimig" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yimig" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:zhangyiming@programmer.net" title="E-Mail → mailto:zhangyiming@programmer.net" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://leetcode.com/yimig/" title="LeeCode → https:&#x2F;&#x2F;leetcode.com&#x2F;yimig&#x2F;" rel="noopener" target="_blank"><i class="fa fa-fw fa-code"></i>LeeCode</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/tim-2-96" title="zhihu → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;tim-2-96" rel="noopener" target="_blank"><i class="fa fa-fw fa-question-circle"></i>zhihu</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://upane.cn/" title="https:&#x2F;&#x2F;upane.cn" rel="noopener" target="_blank">博客旧址</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tim</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">183k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:46</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_sphere.min.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : 'a876807f33858291f9d9',
      clientSecret: '7a5c6a83611c309965d7339d7ca5f16e34a21e9f',
      repo        : 'yimig.github.io',
      owner       : 'yimig',
      admin       : ['yimig'],
      id          : '85c40ea6ed72fc871c4de9de80853098',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
</html>
